<template>
  <div>
    <el-dialog
      title="设备详情"
      :visible.sync="showDialog"
      width="55%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-scrollbar class="scroll-container">
        <div class="el-form">
          <div class="el-form-title">基础信息</div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              设备名称：
              <span>{{ formData.equipmentName }}</span>
            </div>

            <div class="el-form-line-content">
              所属设备型号：
              <span>{{ formData.equModelCode}}</span>
            </div>
            <!-- <div class="el-form-line-content">
              生产日期：
              <span>{{ formData.produceDate }}</span>
            </div>-->
            <div class="el-form-line-content">
              农机码：
              <span>{{ formData.imei}}</span>
            </div>
            <div class="el-form-line-content">
              出厂序号：
              <span>{{ formData.serialNumber}}</span>
            </div>
            <div class="el-form-line-audio">
              设备图片
              <div class="el-form-img" id="el-form-img">
                <el-image
                  v-for="(item,index) in uploadPictureList"
                  :key="index"
                  :src="item"
                  :preview-src-list="uploadPictureList"
                  class="audio-container"
                />
              </div>
            </div>
          </div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              是否展示工况数据：
              <span>{{ formData.operationMode?yesOrNoList[formData.operationMode]:'' }}</span>
            </div>
            <div class="el-form-line-content">
              是否可自动驾驶：
              <span>{{formData.selfDriving? yesOrNoList[formData.selfDriving]:'' }}</span>
            </div>
            <div class="el-form-line-content">
              品牌：
              <span>{{ formData.brand}}</span>
            </div>
            <div class="el-form-line-content">
              生产企业：
              <span>{{ formData.manufacturer}}</span>
            </div>
            <div class="el-form-line-audio">
              设备视频：
              <div class="el-form-img">
                <video
                  v-for="(item,index) in videoUrlList"
                  :key="index"
                  :src="item"
                  controls
                  class="audio-container"
                />
              </div>
            </div>
            <!-- <div class="el-form-line-content">
              质保期：
              <span>{{ formData.sellByDate? formData.sellByDate+'月':'' }}</span>
            </div>-->
          </div>
          <div class="el-form-footer"></div>
        </div>

        <div class="el-form">
          <div class="el-form-title">购置信息</div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              设备名称：
              <span>{{ formData1.equipmentName }}</span>
            </div>

            <div class="el-form-line-content">
              购置数量：
              <span>{{ formData1.num }}{{ unitArr[formData1.unitNo] }}</span>
            </div>
            <div class="el-form-line-content">
              购置日期：
              <span>{{ formData1.purchaseDate}}</span>
            </div>
            <div class="el-form-line-content">
              购置补贴金额：
              <span>{{ formData1.subsidy?formData1.subsidy+'元':'' }}</span>
            </div>
          </div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              设备质保日期：
              <span>{{ formData.warrantyDate}}</span>
            </div>
            <div class="el-form-line-content">
              购置总金额：
              <span>{{formData1.total?formData1.total+'元':'' }}</span>
            </div>
            <div class="el-form-line-content">
              供应商：
              <span>{{formData1.taxpayerNumber }}</span>
            </div>
            <div class="el-form-line-content">
              备注：
              <span>{{formData1.remark }}</span>
            </div>
          </div>
          <div class="el-form-footer"></div>
        </div>

        <div class="el-form">
          <div class="el-form-title">报废信息</div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              设备名称：
              <span>{{ formData2.equipmentName }}</span>
            </div>

            <div class="el-form-line-content">
              报废补贴金额：
              <span>{{ formData2.subsidy?formData2.subsidy+'元':'' }}</span>
            </div>
            <div class="el-form-line-content">
              备注：
              <span>{{ formData2.remark }}</span>
            </div>
          </div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              已使用(天)：
              <span>{{ formData2.used}}</span>
            </div>

            <div class="el-form-line-content">
              报废日期：：
              <span>{{ formData2.scrapDate}}</span>
            </div>
          </div>
          <div class="el-form-footer"></div>
        </div>

        <div class="el-form">
          <div class="el-form-title">其他信息</div>
          <div class="el-form-line">
            <div class="el-form-line-content">
              设备说明书：
              <div class="file-list">
                <div
                  class="pointer"
                  v-for="item,index in docuemntList"
                  :key="index"
                  @click="view(item)"
                >{{item.fileName}}</div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>

      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button
          v-if="judgePermission(138,'edit')"
          type="primary"
          class="savebtn"
          @click="save()"
        >确定</el-button>
      </div>
    </el-dialog>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body top="0">
      <iframe
        id="iframe"
        v-if="dialogImageUrlName.includes('.pdf') || dialogImageUrlName.includes('.txt')"
        class="iframe"
        :src="page_url"
        frameborder="0"
        width="100%"
      />
      <iframe
        v-else
        id="iframe"
        class="iframe"
        :src="'https://view.officeapps.live.com/op/view.aspx?src=' + dialogImageUrl"
        controls
        muted
        width="100%"
      />
    </el-dialog>
    <!-- 预览视频 -->
    <el-dialog :visible.sync="dialogViewVideo" append-to-body top="0">
      <video :src="dialogVideo" controls width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import equipScrapRecordApi from "@/api/equip-manage/equip-scrap-record";
import equipPurchaseRecordApi from "@/api/equip-manage/equip-purchase-record";
import documentApi from "@/api/document";
import dataItemManageApi from "@/api/basic-info-manage/data-item-manage";
import { mapGetters } from "vuex";
import UploadPics from "@/components/UploadPics/upload-img-list.vue";
import UploadDocument from "@/components/UploadPics/upload-document-list.vue";
import axios from "axios";
export default {
  name: "",
  components: { UploadPics, UploadDocument },
  props: {
    nowChanceStau: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      },
    },
    equModelArr: {
      type: [Array],
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      dialogVisible: false, // 图片弹窗
      dialogImageUrl: "", // 预览图片
      dialogImageUrlName: "", // 预览图片
      page_url: "",
      dialogViewVideo: false, // 视频弹窗
      dialogVideo: "", // 预览视频
      loading: true, // 加载效果

      //存放视频的数组
      videoUrlList: [],
      //存放文档的数组
      docuemntList: [],
      // 选中的tab页
      activeName: "first",
      //图片预览状态
      dialogVisible: false,
      // 存放图片列表的数组
      uploadPictureList: [],
      //图片预览url
      dialogImageUrl: "",
      pictureData: "",
      pictureList: [],
      formData: {},

      yesOrNoList: [
        { name: "是", id: 0 },
        { name: "否", id: 1 },
      ],
      // 添加修改
      parameterList: [],
      formData1: {},

      // 单位
      unitArr: [],
      formData2: {},

      equipmentArr: [],
      showDialog: this.show,
      // 报废信息
      scrapObject: {},
      // 购置信息
      purchaseObject: {},
      scrapNowChanceStau: "add",
      purchaseNowChanceStau: "add",
      acept: "",
      acct: "",
      statusArr: [
        {
          name: "启用",
          id: "ENABLE",
        },
        {
          name: "废弃",
          id: "DISCARD",
        },
        {
          name: "维修中",
          id: "REPAIRING",
        },
        {
          name: "禁用",
          id: "DISABLE",
        },
      ],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    show(v) {
      this.showDialog = v;
    },
    editObject(v) {
      if (v && v.equipmentCode) {
        this.formData1 = {
          equipmentCode: this.editObject.equipmentCode,
          equipmentName: this.editObject.equipmentName,
        };
        this.formData2 = {
          equipmentCode: this.editObject.equipmentCode,
          equipmentName: this.editObject.equipmentName,
        };
        this.formData = this.editObject;
        console.log("editObject", this.formData);
        (this.formData.operationMode =
          this.editObject.operationMode === false ? 1 : 0),
          (this.formData.selfDriving =
            this.editObject.selfDriving === false ? 1 : 0),
          console.log("editObject2", this.formData);
        this.scrapNowChanceStau = "";
        this.purchaseNowChanceStau = "";
        this.scrapObject = {};
        this.purchaseObject = {};
        this.queryScrap(v.equipmentCode);
        this.queryPurchase(v.equipmentCode);
        this.queryDocument(v.equipmentCode);
      }
    },
    "formData.produceDate": {
      deep: true,
      handler(v) {
        if (v && this.formData.sellByDate) {
          var dt = new Date(v);
          dt.setMonth(dt.getMonth() + this.formData.sellByDate);
          //  document.write( dt );
          this.$set(this.formData, "warrantyDate", this.dateToFormatTwo(dt));
        } else {
          this.$set(this.formData, "warrantyDate", "");
        }
      },
    },
    "formData.sellByDate": {
      deep: true,
      handler(v) {
        if (v && this.formData.produceDate) {
          var dt = new Date(this.formData.produceDate);
          dt.setMonth(dt.getMonth() + v);
          //  document.write( dt );
          this.$set(this.formData, "warrantyDate", this.dateToFormatTwo(dt));
        } else {
          this.$set(this.formData, "warrantyDate", "");
        }
      },
    },
  },
  created() {},
  mounted() {
    this.queryUnitList();
    this.queryEquipment();
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },

    async queryDocument(params) {
      // 查询当前设备图片
      documentApi.queryPictureList(params).then((res) => {
        if (res.code === 1) {
          let data = res.data;
          this.uploadPictureList = [];
          if (data.length > 0) {
            data.forEach((a) => {
              this.uploadPictureList.push(a.filePath || 'data:application/*;base64,'  + a.pictureData);
            });
          }
        }
      });
      //查询当前设备视频id
      const res = await documentApi.queryVideoIdList(params);
      if (res.code === 1) {
        console.log(res);
        this.videoUrlList = [];
        if (res.data.length > 0) {
          res.data.forEach((a) => {
            this.videoUrlList.push(a.filePath || 'data:application/*;base64,'  + a.pictureData);
          });
          // this.videoUrl = `https://gateway.matefarm.net/v3/equipment-base/v1/equipmentVideo/getFileById?equipmentVideoId=${this.videoUrlList[0].equipmentVideoId}&databaseName=${sessionStorage.databaseName}`;
        }
      }
      //查询当前设备文档文件
      documentApi.queryDocument(params).then((res) => {
        if (res.code === 1) {
          console.log("---", res.data);
          let data = res.data;
          this.docuemntList = data;
          if (this.docuemntList.length > 0) {
            this.docuemntList.forEach((a) => {
              this.$set(a, "url", a.filePath);
              a.name = a.fileName;
            });
          }
        }
      });
    },

    // 预览
    view(file) {
      console.log(file);
      this.dialogVisible = true; // 图片弹窗
      this.dialogImageUrl = file.url; // 预览图片
      this.dialogImageUrlName = file.fileName; //
      this.makePdf(file.url);
      // console.log('预览',file);
    },
    makePdf(url) {
      // 把孙悟空替换为了猪八戒
      var newstr = url.replace(/%26/g, "&");
      //  console.log(newstr);
      axios.get(newstr, { responseType: "blob" }).then((res) => {
        const { data, status } = res;
        let binaryData = [];
        binaryData.push(data); // res 后台返回的流数据
        let pdfUrl = "";
        pdfUrl = window.URL.createObjectURL(
          new Blob(binaryData, { type: "application/pdf" })
        );
        this.page_url = pdfUrl;
      });
    },
    //文档下载
    downPDF(file) {
      console.log(file);
      documentApi
        .downPDF({ equipmentFileId: file.equipmentFileId })
        .then((res = {}) => {
          if (window.navigator.msSaveBlob) {
            // IE
            //IE无法打开Blob URL链接，所以不能预览只能通过window.navigator.msSaveBlob下载
            //注：msSaveBlob的第二个参数要有.pdf后缀，不然IE下载后是没有后缀的文件
            const blob = new window.Blob([res.data], {
              type: "application/pdf;charset-UTF-8",
            });
            window.navigator.msSaveBlob(blob, `${filename}.pdf`);
          } else {
            const blob = new window.Blob([res], {
              type: "application/pdf;charset-UTF-8",
            });
            const href = URL.createObjectURL(blob);
            window.open(href);
          }
        });
    },
    queryScrap(params) {
      equipScrapRecordApi.query(params).then((res) => {
        if (res.code === 1) {
          let data = res.data || {};
          this.scrapObject = data;
          if (this.scrapObject.equipmentCode) {
            this.scrapNowChanceStau = "edit";
            this.formData2 = this.scrapObject;
          } else {
            this.scrapNowChanceStau = "add";
          }
        }
      });
    },
    queryPurchase(params) {
      equipPurchaseRecordApi.query(params).then((res) => {
        if (res.code === 1) {
          let data = res.data || {};
          this.purchaseObject = data;
          if (this.purchaseObject.equipmentCode) {
            this.purchaseNowChanceStau = "edit";
            this.formData1 = this.purchaseObject;
          } else {
            this.purchaseNowChanceStau = "add";
          }
        }
      });
    },
    // 单位
    queryUnitList() {
      this.unitArr = [];
      dataItemManageApi.queryUnit({}).then((res) => {
        if (res.code === 1) {
          let data = res.data || {};
          this.unitArr = data;
        } else {
          this.$message.error("单位名称给获取失败");
        }
      });
    },
    queryEquipment() {
      this.equipmentArr = [];
      equipScrapRecordApi.queryEquipment({}).then((res) => {
        if (res.code === 1) {
          let data = res.data || [];
          for (var i in data) {
            this.equipmentArr.push({
              equipmentName: data[i],
              equipmentCode: i,
            });
          }
        }
      });
    },
    save() {
      this.editStatus = true;
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
      this.editStatus = true;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog__body {
    height: 55vh;
    overflow: hidden;
  }
  .dialog {
    display: flex;
    flex-direction: column;
    overflow-y: auto;
  }
  .scroll-container {
    white-space: nowrap;
    overflow: hidden;
    overflow-y: scroll;
    width: 100%;
    height: 100%;
    ::v-deep {
      .el-scrollbar__bar {
        bottom: 0px;
      }
      .el-scrollbar__wrap {
        height: 49px;
      }
    }
  }
  .el-form {
    display: flex;
    width: 100%;
    justify-content: flex-start;
    align-content: flex-start;
    .el-form-title {
      width: 100%;
      height: 40px;
      color: #006e91;
      font-weight: bold;
      font-size: 17.33px;
    }
    .el-form-line {
      flex: 1;
      align-items: flex-start;
      .el-form-line-content {
        height: 32px;
        color: #000000;
        font-size: 16px;
        font-weight: 400;
        font-family: Microsoft YaHei;
        font-weight: 400;
        .file-list {
          display: flex;
          width: 100%;
          align-items: flex-start;
          justify-content: flex-start;
          flex-wrap: wrap;
          .pointer {
            display: flex;
            position: relative;
            align-items: center;
            margin-bottom: 15px;
            margin-right: 10px;
            width: 18%;
            height: 70px;
            border: 1px solid #000;
            cursor: pointer;
            font-size: 13px;
            white-space: pre-line;

            &:hover {
              background: rgba(0, 0, 0, 0.5);
            }
          }
        }
      }
      .el-form-line-audio {
        display: flex;
        flex-direction: column;
        width: 90%;
        margin-bottom: 15px;
        color: #000000;
        font-size: 16px;
        font-weight: 400;
        font-family: Microsoft YaHei;
        font-weight: 400;
        .el-form-img {
          display: flex;
          width: 100%;
          align-items: flex-start;
          flex-wrap: wrap;
          overflow: auto;
          height: 300px;
        }
        .audio-container {
          width: 48%;
          height: 100px;
          margin-top: 10px;
          object-fit: contain;
          &:nth-child(2n) {
            margin-left: 10px;
          }
        }
      }
    }

    .el-form-footer {
      width: 100%;
      height: 1px;
      margin-bottom: 20px;
      background-color: #ced1d7;
    }
  }
}
.add-many {
  border: 1px solid #6ecae3;
  width: 40px;
  height: 40px;
  padding: 0;
  background-color: transparent;
  line-height: 40px;
  border-radius: 4px;
  color: rgb(161, 154, 154);
  font-weight: 600;
  i {
    font-size: 40px;
  }
}

.iframe {
  height: 80vh;
}
::v-deep .el-upload-dragger {
  width: 330px;
}
.video-con {
  width: 100%;
  height: 200px;
}
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 160px !important;
}
::v-deep .el-tabs__item.is-active {
  color: #006e91;
}
::v-deep .el-image-viewer__close {
  color: #006e91;
}
::v-deep .el-tabs__item {
  font-size: 16px;
  &:hover {
    color: #006e91;
  }
}
::v-deep .el-tabs__active-bar {
  background-color: #006e91;
}
</style>
